package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.beans.TableProcess;
import com.google.common.base.CaseFormat;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.*;
import java.util.*;

/**
 * @author Felix
 * @date 2023/9/26
 * 判断是否是维度数据
 */
public class TableProcessFunction extends BroadcastProcessFunction<JSONObject, TableProcess, JSONObject> {
    private MapStateDescriptor<String, TableProcess> mapStateDescriptor;
    private Map<String,TableProcess> configMap = new HashMap<>();

    public TableProcessFunction(MapStateDescriptor<String, TableProcess> mapStateDescriptor) {
        this.mapStateDescriptor = mapStateDescriptor;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        //将配置表中的配置信息预加载到程序中
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //建立连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/gmall0417_config?" +
            "user=root&password=123456&useUnicode=true&characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");
        //获取数据库操作对象
        String sql = "select * from gmall0417_config.table_process_dim ";
        PreparedStatement ps = conn.prepareStatement(sql);
        //执行SQL
        ResultSet rs = ps.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        //处理结果集
        while (rs.next()){
            JSONObject jsonObj = new JSONObject();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object columnValue = rs.getObject(i);
                jsonObj.put(columnName,columnValue);
            }
            TableProcess tableProcess = jsonObj.toJavaObject(TableProcess.class);
            configMap.put(tableProcess.getSourceTable(),tableProcess);
        }
        //释放资源
        rs.close();
        ps.close();
        conn.close();
    }

    //处理主流数据
    @Override
    public void processElement(JSONObject jsonObj, ReadOnlyContext ctx, Collector<JSONObject> out) throws Exception {
        // {"database":"gmall0417","data":{"tm_name":"Redmi","create_time":"2021-12-14 00:00:00","logo_url":"/a/b/c.jps","id":1},"old":{},"type":"update","table":"base_trademark","ts":1695693998}
        // System.out.println(jsonObj);
        //获取当前处理的这条数据的表名
        String table = jsonObj.getString("table");
        //获取广播状态
        ReadOnlyBroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        //判断是否为维度数据（根据表名到广播状态中获取对应的配置信息）
        TableProcess tableProcess = null;

        if((tableProcess = broadcastState.get(table))!=null
            || (tableProcess = configMap.get(table))!=null){
            //如果tableProcess不为空，说明在广播状态中找到了对应的维度信息，处理的主流数据是维度，发送到下游
            //{"tm_name":"Redmi","create_time":"2021-12-14 00:00:00","logo_url":"/a/b/c.jps","id":1}
            JSONObject dataJsonObj = jsonObj.getJSONObject("data");

            //过滤掉不需要传递的属性
            String sinkColumns = tableProcess.getSinkColumns();
            filterColumn(dataJsonObj,sinkColumns);
            //在向下游传递数据前，补充操作类型
            String type = jsonObj.getString("type");
            dataJsonObj.put("type",type);
            //在向下游传递数据前，补充相关配置信息
            dataJsonObj.put("table_process",tableProcess);
            // {"tm_name":"Redmi123","create_time":"2021-12-14 00:00:00","logo_url":"/a/b/c.jps","id":1,"type":"update","table_process":{"op":"r","sinkColumns":"id,tm_name","sinkFamily":"info","sinkRowKey":"id","sinkTable":"dim_base_trademark","sourceTable":"base_trademark"}}
            out.collect(dataJsonObj);
        }
    }

    //过滤掉不需要传递的属性
    //dataJsonObj :{"tm_name":"Redmi","create_time":"2021-12-14 00:00:00","logo_url":"/a/b/c.jps","id":1}
    //sinkColumns :id,tm_name
    private void filterColumn(JSONObject dataJsonObj, String sinkColumns) {
        String[] columnArr = sinkColumns.split(",");
        List<String> columnList = Arrays.asList(columnArr);
        Set<Map.Entry<String, Object>> entrySet = dataJsonObj.entrySet();
        entrySet.removeIf(entry->!columnList.contains(entry.getKey()));
    }

    //处理广播流数据
    @Override
    public void processBroadcastElement(TableProcess tableProcess, Context ctx, Collector<JSONObject> out) throws Exception {
        //获取广播状态
        BroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        //获取对配置表的操作的类型
        String op = tableProcess.getOp();
        String key = tableProcess.getSourceTable();
        if ("d".equals(op)) {
            //从广播状态中将对应的配置信息删除掉
            broadcastState.remove(key);
            configMap.remove(key);
        } else {
            //将对应的配置信息添加或者更新到广播状态中
            broadcastState.put(key, tableProcess);
            configMap.put(key,tableProcess);
        }
    }
}
